package com.czh.listener;

import com.czh.constant.CommonConstant;
import com.czh.utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 直连模式消费者
 *
 * @author chenzhihua
 * @Date 2024/7/29
 */
@Slf4j
@Component
public class RabbitMqListener {
    @Resource
    private RabbitMqUtils rabbitMqUtils;

    @RabbitListener(queues = CommonConstant.TEST1_QUEUE)
    public void test1Consumer(Message message, Channel channel) {
        try {
            //手动确认消息已经被消费
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("Test1消费消息：" + message.toString() + "。成功！");
        } catch (Exception e) {
            rabbitMqUtils.sendByRoutingKey(CommonConstant.ERROR_EXCHANGE_NAME, CommonConstant.ERROR_ROUTINGKEY, message);
            e.printStackTrace();
            log.info("Test1消费消息：" + message.toString() + "。失败！");
        }
    }

    @RabbitListener(queues = CommonConstant.TEST2_QUEUE)
    public void test2Consumer(Message message, Channel channel) {
        try {
            int i = 1 / 0;
            //手动确认消息已经被消费
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("Test2消费消息：" + message.toString() + "。成功！");
        } catch (Exception e) {
            //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
            rabbitMqUtils.sendByRoutingKey(CommonConstant.ERROR_EXCHANGE_NAME, CommonConstant.ERROR_ROUTINGKEY, message);
            e.printStackTrace();
            log.info("Test2消费消息：" + message.toString() + "。失败！");
        }
    }

    // 消费延迟消息
    @RabbitListener(queues = CommonConstant.DLQ)
    public void lazyConsumer(Message message, Channel channel) {
        try {
            //手动确认消息已经被消费
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("Test2消费消息：" + message.toString() + "。成功！");
        } catch (Exception e) {
            //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
            rabbitMqUtils.sendByRoutingKey(CommonConstant.ERROR_EXCHANGE_NAME, CommonConstant.ERROR_ROUTINGKEY, message);
            e.printStackTrace();
            log.info("Test2消费消息：" + message.toString() + "。失败！");
        }
    }
}
